package com.jd.platform.gobrs.worker.keydispatcher;

import com.jd.platform.gobrs.common.model.GCacheKeyModel;
import com.jd.platform.gobrs.common.model.typeenum.CacheType;
import com.jd.platform.gobrs.worker.keylistener.AutoKeyListener;
import com.jd.platform.gobrs.worker.keylistener.IKeyListener;
import com.jd.platform.gobrs.worker.keylistener.KeyEventOriginal;
import com.jd.platform.gobrs.worker.keylistener.ManualKeyListener;
import com.jd.platform.gobrs.worker.tool.InitConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;


/**
 * 热key 消费者
 *
 * @author sizegang
 * @version 1.0
 * @date 2020-06-09
 */
@Component
@Scope("prototype")
public class KeyConsumer {

    @Autowired
    private ManualKeyListener manualKeyListener;

    @Autowired
    private AutoKeyListener autoKeyListener;

    public void beginConsume() {
        while (true) {
            try {
                GCacheKeyModel model = DispatcherConfig.QUEUE.take();
                // 如果是删除事件
                if (CacheType.MANUAL.equals(model.getCacheType()) && model.isRemove()) { // 手动设置规则
                    manualKeyListener.removeKey(model, KeyEventOriginal.CLIENT);
                } else if (CacheType.MANUAL.equals(model.getCacheType())) { // 手动设置规则
                    autoKeyListener.newKey(model, KeyEventOriginal.CLIENT);
                } else if (CacheType.AUTO.equals(model.getCacheType()) && model.isRemove()) {// 自动智能
                    autoKeyListener.removeKey(model, KeyEventOriginal.CLIENT);
                } else if (CacheType.AUTO.equals(model.getCacheType())) { // 自动智能
                    autoKeyListener.newKey(model, KeyEventOriginal.CLIENT);
                }
                //处理完毕，将数量加1
                InitConstant.totalDealCount.increment();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
